<template>
	<div class="blog-category-container" v-loading="isDataLoading">
		<h2>文章分类</h2>
		<right-list :list="list" @select="handleSelect"></right-list>
	</div>
</template>

<script>
import RightList from './RightList.vue'
import fetchData from '@/mixins/fetchData'
import * as blogApi from '@/api/blog'
export default {
	name: 'BlogCategory',
	mixins: [fetchData([])],
	components: { RightList },
	computed: {
		categoryId() {
			return this.$route.params.categoryId || -1 // 因为有逻辑判断，没有则直接写
		},
		// 计算属性：1.根据categoryId来给data加上isSelect
		list() {
			// 数组加个全部作为第一项
			const resList = [
				{
					id: -1,
					name: '全部',
					articleCount: this.data.reduce((a, b) => a + b.articleCount, 0),
					order: 1,
				},
				...this.data,
			]

			const newList = resList.map((item) => ({
				...item,
				isSelect: item.id === this.categoryId ? true : false,
				aside: `${item.articleCount}篇`,
			}))
			return newList
		},
	},
	methods: {
		async fetchData() {
			return await blogApi.getBlogTypes()
		},
		handleSelect(item) {
			// 这里就要代码级别router了
			// this.isDataLoading = true // 解决BUG，v-loading互相影响
			if (item.id === -1) {
				this.$router.push({
					name: 'blog',
					query: { ...this.$route.query, page: 1 },
				})
			} else {
				this.$router.push({
					name: 'categoryBlog',
					params: {
						categoryId: item.id,
					},
					query: { ...this.$route.query, page: 1 },
				})
			}
		},
	},
}
</script>

<style lang="less" scoped>
.blog-category-container {
	width: 300px;
	height: 100%;
	padding: 20px;
	overflow: auto;
	position: relative;
	h2 {
		font-weight: 700;
		letter-spacing: 2px;
		font-size: 1em;
		margin-bottom: 20px;
	}
}
</style>
